import { login, getUserInfo, getUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
export default {
  namespaced: true,
  strict: true,
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      // 存入cookie
      setToken(token)
    },
    // 获取用户数据
    setuserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    // 清除用户数据-退出
    removeuserInfo(state) {
      state.token = ''
      state.userInfo = {}
      removeToken()
    },
    // token失效处理
    removetk(state) {
      state.token = ''
      state.userInfo = {}
    }
  },
  actions: {
    async fetchLogin(ctx, data) {
      const res = await login(data)
      ctx.commit('setToken', res)
    },
    async fetchUserInfo(ctx) {
      const res = await getUserInfo()
      const detailRes = await getUserDetailById(res.userId)
      ctx.commit('setuserInfo', { ...res, ...detailRes })
      return res
    }
  }
}
